#include "free_parser.h"

void		free_cmpdlist(s_cmpdlist	*clist)
{
  if (clist != NULL)
  {
    free_andor(clist->andor);
  }

  free(clist);
}

void		free_funcdec(s_funcdec		*funcdec)
{
  if (funcdec != NULL)
    free_sh_cmd(funcdec->sh_cmd);

  free(funcdec);
}

void		free_sh_cmd(s_sh_cmd		*sh_cmd)
{
  if (sh_cmd != NULL)
    {
      free_cmpdlist(sh_cmd->cmpdlist);
      free_rulefor(sh_cmd->rulefor);
      free_ruleif(sh_cmd->ruleif);
      free_ruleuntil(sh_cmd->ruleuntil);
      free_rulecase(sh_cmd->rulecase);
      free_rulewhile(sh_cmd->rulewhile);
    }

  free(sh_cmd);
}

void		free_cmd(s_command              *cmd)
{
  s_command	*tmp = NULL;

  while (cmd != NULL)
  {
    free_smp_cmd(cmd->smp_cmd);
    free_sh_cmd(cmd->sh_cmd);
    free_funcdec(cmd->funcdec);

    tmp = cmd;
    cmd = cmd->next;
    free(tmp);
  }
}

static void     free_elt(s_element      *elt)
{
  if (elt != NULL)
    free_word(elt->word);

  free(elt);
}

void		free_smp_cmd(s_smp_cmd  *smp_cmd)
{
  s_prefix      *tmp = NULL;
  s_prefix	*aux = NULL;
  s_element	*elttmp = NULL;
  s_element	*eltaux = NULL;

  if (smp_cmd != NULL)
  {
    tmp = smp_cmd->prefix;
    elttmp = smp_cmd->elt;

    while (tmp != NULL)
    {
      aux = tmp;
      tmp = tmp->next;
      free(aux);
    }

    while (elttmp != NULL)
    {
      eltaux = elttmp;
      elttmp = elttmp->next;
      free_elt(eltaux);
    }

    free(smp_cmd);
  }
}
